<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    EveBit_Library
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: functions.php 130 2011-03-18 03:10:02Z cheng.wei $$
 * @copyright   Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Change first letter to lower
 * 
 * @param string $str
 * @return string
 */
function ulfirst($str) {
	return strtolower(substr($str, 0, 1)) . substr($str, 1);
}

/**
 * Tiny function to enhance functionality of ucwords
 *
 * Will capitalize first letters and convert separators if needed
 *
 * @param string $str
 * @param string $destSep
 * @param string $srcSep
 * @return string
 */
function uc_words($str, $destSep = '_', $srcSep = '_') {
	return str_replace(' ', $destSep, ucwords(str_replace($srcSep, ' ', $str)));
}

/**
 * Check whether sql date is empty
 *
 * @param string $date
 * @return boolean
 */
function is_empty_date($date) {
	return preg_replace('#[ 0:-]#', '', $date) === '';
}

/**
 * XML to array (from file)
 * @param string $file
 * @return array|string|null
 */
function xml2array_string($file) {
	$xml = simplexml_load_file($file);
	if (!$xml) {
		return null;
	}
	$result = xml2array($xml);
	unset($xml);
	return $result;
}

/**
 * XML to array (from file)
 * @param string $file
 * @return array|string|null
 */
function xml2array_file($file) {
	$xml = simplexml_load_file($file);
	if (!$xml) {
		return null;
	}
	$result = xml2array($xml);
	unset($xml);
	return $result;
}

/**
 * XML to array
 * @param SimpleXMLElement $xml
 * @return array|string|null
 */
function xml2array($xml, $ns = null) {
	if (!($xml instanceof SimpleXMLElement)) {
		return $xml;
	}
	
	// TODO: special namespaces
	if (is_string($ns)) {
		$attrs = $xml->attributes($ns,true);
		$childs = $xml->children($ns,true);
	} else {
		$attrs = $xml->attributes();
		$childs = $xml->children();
	}
	
	if (!$attrs && !$childs) {
		return trim($xml);
	}
	
	$result = array();
	foreach ($attrs as $attr) {
		$result[$attr->getName()] = trim($attr);
	}
	
	if (!$childs) {
		$value = trim($xml);
		if ($value || !isset($result['value'])) {
			$result['value'] = $value;
		}
	} else {
		$hasNames = array();
		foreach ($childs as $child) {
			$name = $child->getName();
			$value = xml2array($child);
			if (!isset($result[$name])) {
				$result[$name] = $value;
			} else if (!in_array($name, $hasNames)) {
				$hasNames[] = $name;
				$result[$name] = array($result[$name]);
				$result[$name][] = $value;
			} else {
				$result[$name][] = $value;
			}
		}
	}
	
	return $result;
}
